package com.chuangke.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chuangke.common.constant.CacheKeyConstants;
import com.chuangke.system.dao.mapper.SysAphorismMapper;
import com.chuangke.system.entity.SysAphorism;
import com.chuangke.system.service.SysAphorismService;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;

@Service
public class SysAphorismServiceImpl implements SysAphorismService {

    @Autowired
    private SysAphorismMapper sysAphorismMapper;

    @CacheEvict(cacheNames = CacheKeyConstants.SYS_APHORISM, key = "'" + CacheKeyConstants.SYS_APHORISM + "'")
    @Override
    public void save(SysAphorism record) {
        sysAphorismMapper.insert(record);
    }

    @CacheEvict(cacheNames = CacheKeyConstants.SYS_APHORISM, key = "'" + CacheKeyConstants.SYS_APHORISM + "'")
    @Override
    public void delete(String id) {
        sysAphorismMapper.deleteById(id);
    }

    @CacheEvict(cacheNames = CacheKeyConstants.SYS_APHORISM, key = "'" + CacheKeyConstants.SYS_APHORISM + "'")
    @Override
    public void update(SysAphorism record) {
        sysAphorismMapper.updateById(record);
    }

    @Cacheable(cacheNames = CacheKeyConstants.SYS_APHORISM, key = "'" + CacheKeyConstants.SYS_APHORISM + "'")
    @Override
    public List<SysAphorism> findAll() {
        return sysAphorismMapper.selectList(new QueryWrapper<>());
    }

    @Override
    public SysAphorism findRandom() {
        List<SysAphorism> list = ((SysAphorismService) AopContext.currentProxy()).findAll();
        SysAphorism sysAphorism = null;
        if (list != null && !list.isEmpty()) {
            Random rand = new Random();
            sysAphorism = list.get(rand.nextInt(list.size()));
        }
        return sysAphorism;
    }

}
